package com.codingke.codingbookstore.ui;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;

import com.codingke.codingbookstore.R;
import com.codingke.codingbookstore.adapter.AddressListItemAdapter;
import com.codingke.codingbookstore.vo.Address;
import com.codingke.codingbookstore.vo.User;

import java.util.ArrayList;
import java.util.List;

import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.listener.FindListener;

public class AddressManagerActivity extends BaseActivity implements AdapterView.OnItemClickListener{

    private ListView listView2_address;
    private AddressListItemAdapter addressListItemAdapter;
    private ArrayList<Address> addresses = new ArrayList<>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_address_manager);
        listView2_address = (ListView) findViewById(R.id.listView2_address);
        listView2_address.setOnItemClickListener(this);
        addressListItemAdapter = new AddressListItemAdapter(this,addresses,R.layout.address_list_item2);
        listView2_address.setAdapter(addressListItemAdapter);
    }

    @Override
    protected void onResume() {
        super.onResume();
        initData();
    }

    private void initData(){
        addresses = (ArrayList<Address>) getIntent().getSerializableExtra("addresses");
        if(addresses==null){
            BmobQuery<Address> query = new BmobQuery<>();
            query.addWhereEqualTo("userId",BmobUser.getCurrentUser(this, User.class).getObjectId());
            query.order("-isDefault");//排序isDefault降序
            query.findObjects(this, new FindListener<Address>() {
                @Override
                public void onSuccess(List<Address> list) {
                    addresses = (ArrayList<Address>) list;
                    addressListItemAdapter.setAddresses(addresses);
                    addressListItemAdapter.notifyDataSetChanged();
                }

                @Override
                public void onError(int i, String s) {
                    showToast("查找地址失败");
                }
            });

        }else{
            addressListItemAdapter.setAddresses(addresses);
            addressListItemAdapter.notifyDataSetChanged();
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

        Intent intent = new Intent(this,EditAddressActivity.class);
        intent.putExtra("address",addresses.get(position));
        startActivity(intent);
        finish();
    }

    /**
     * 添加地址界面
     * @param view
     */
    public void addAddressClick(View view){
        startActivity(new Intent(this,AddAddressActivity.class));
        finish();
    }

}
